#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
 
int main(int argc, char *argv[]) {
    if (argc < 2)
        return -1;
    
    char *type = argv[1];
    printf("Wait test type: %s\n", type);

    pid_t pid;
    pid = fork();

    if (pid < 0) {
        perror("fork failed");
        exit(1);
    }

    if (pid == 0) {
        if (strcmp(type, "exit") == 0) {
            printf("Child: exit in code 3\n");
            exit(3);
        } else if (strcmp(type, "error") == 0) {
            printf("Child: zero division error\n");
            int i = 5, j = 0;
            i /= j;
        } else if (strcmp(type, "custom") == 0) {
            printf("Child: is running, %d\n", getpid());
            while(1) {}
        } else if (strcmp(type, "stop") == 0) {
            printf("Child: the process will stop itself\n");
            raise(SIGSTOP);
            printf("Child: running after first stop\n");
            sleep(3);
            exit(3);
        }
    } else {
        int stat_val;
        sleep(1);
        kill(pid, SIGSTOP);

        waitpid(pid, &stat_val, 0);

        if (WIFEXITED(stat_val))
            printf("Parent: Child exited with code %d\n", WEXITSTATUS(stat_val));
        else if (WIFSIGNALED(stat_val))
            // SIGTERM15/SIGKILL9/SIGSTVEC
            printf("Parent: child terminated by signal %s(%d)\n", strsignal(WTERMSIG(stat_val)), WTERMSIG(stat_val));
        else if(WIFSTOPPED(stat_val)) {
            // SIGSTSP/SIGSTOP
            printf("Parent: child stopped by signal %s(%d)\n", strsignal(WSTOPSIG(stat_val)), WSTOPSIG(stat_val));
        } else {
            printf("%d", stat_val);
        }
    }
    return 0;
}